import type { RouteRecordRaw } from 'vue-router';
import type { App } from 'vue';

import { createRouter, createWebHashHistory } from 'vue-router';
import { basicRoutes } from './routes';

// 白名单应该包含基本静态路由
const WHITE_NAME_LIST: string[] = [];
const getRouteNames = (array: any[]) =>
   array.forEach((item) => {
      WHITE_NAME_LIST.push(item.name);
      // 子路径都给包括进来,这个没有跳出条件——因为放在了foreach的大环境先判断了
      getRouteNames(item.children || []);
   });
// 基础路径上面的都设置为白名单
getRouteNames(basicRoutes);

// app router
export const router = createRouter({
   history: createWebHashHistory(import.meta.env.VITE_PUBLIC_PATH),
   routes: basicRoutes as unknown as RouteRecordRaw[],
   strict: true,
   scrollBehavior: () => ({ left: 0, top: 0 }),
});

// reset router
export function resetRouter() {
   router.getRoutes().forEach((route) => {
      const { name } = route;
      if (name && !WHITE_NAME_LIST.includes(name as string)) {
         //注意这句的理解,两个都执行,如果前面的假就不执行了
         router.hasRoute(name) && router.removeRoute(name);
      }
   });
}

// config router
export function setupRouter(app: App<Element>) {
   app.use(router);
}
